import * as faceapi from "face-api.js";

let withBoxes = true

main()

async function main(){
    // load model
    await faceapi.nets.ssdMobilenetv1.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceLandmark68Net.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceRecognitionNet.loadFromUri('http://127.0.0.1:8888/weights')
    await faceapi.nets.faceExpressionNet.loadFromUri('http://127.0.0.1:8888/weights')

    try {
        const stream = await navigator.mediaDevices.getUserMedia({ video:{} })
        const videoEl = document.getElementById('inputVideo')
        videoEl.srcObject = stream
    } catch (error) {
        const errDom = document.createElement('div')
        errDom.className = 'err-container'
        errDom.innerText = '找不到请求的设备'
        document.querySelector('.page-container').prepend(errDom)
        alert(error.message)
    }

    closeLoading()
}

window.onPlay = async()=>{
    const videoEl = document.getElementById('inputVideo')
    if(videoEl.paused || videoEl.ended){
        return setTimeout(()=>onPlay())
    }

    const result = await faceapi.detectSingleFace(videoEl).withFaceExpressions()
    if(result){
        const canvas = document.getElementById('overlay')
        const dims= faceapi.matchDimensions(canvas, videoEl, true)

        const resizedResult = faceapi.resizeResults(result, dims)
        if(withBoxes){
            faceapi.draw.drawDetections(canvas, resizedResult)
        }
        faceapi.draw.drawFaceExpressions(canvas, resizedResult, 0.05)
    }
    setTimeout(()=>onPlay())
}